angular.module('charity.content',[])
    .controller('contentCtr', ['$scope', '$filter', 'contentService', '$routeParams', '$uibModal','logger',
        function ($scope, $filter, contentService, $routeParams,$uibModal, logger) {
            $scope.stores = [];
            $scope.searchKeywords = '';
            $scope.filteredStores = [];
            $scope.row = '',

            $scope.selectedMenu = {};
            $scope.menus = [];

            $scope.select = function (page) {
                var end, start;
                start = (page - 1) * $scope.numPerPage;
                end = start + $scope.numPerPage;
                return $scope.currentPageStores = $scope.filteredStores.slice(start, end);
            };

            $scope.onFilterChange = function () {
                $scope.select(1);
                $scope.currentPage = 1;
                return $scope.row = '';
            };

            $scope.onNumPerPageChange = function () {
                $scope.select(1);
                return $scope.currentPage = 1;
            };

            $scope.onOrderChange = function () {
                $scope.select(1);
                return $scope.currentPage = 1;
            };

            $scope.changeMenu = function () {
                $scope.search();
            }

            $scope.search = function () {
                contentService.queryAllContents($scope.selectedMenu.menuId).then(function (results) {

                    if(!results || results.code != 0){
                        logger.logError((results && results.message) || '查询数据失败,请重新登录');
                        return;
                    }
                    $scope.stores = results.data || [];

                    $scope.filteredStores = $filter('filter')($scope.stores, $scope.searchKeywords);
                    return $scope.onFilterChange();
                });
            };

            $scope.order = function (rowName) {
                if ($scope.row === rowName) {
                    return;
                }
                $scope.row = rowName;
                $scope.filteredStores = $filter('orderBy')($scope.stores, rowName);
                return $scope.onOrderChange();
            };
            $scope.numPerPageOpt = [3, 5, 10, 20];
            $scope.numPerPage = $scope.numPerPageOpt[2];
            $scope.currentPage = 1;
            $scope.currentPageStores = [];

            $scope.deleteContent = function(content){
                var modalInstance = $uibModal.open({
                    animation: true,
                    templateUrl: 'deleteModalContent.html',
                    controller: 'deleteComponentCtrl',
                    resolve: {
                        data: function () {
                            return {id:content.contentId, name: content.contentName}
                        }
                    }
                });

                modalInstance.result.then(function (contentId) {
                    contentService.deleteContent(contentId).then(function (results) {
                        if(results && results.code == 0){
                            logger.logSuccess('操作成功');
                            $scope.search();

                        }
                        else{
                            logger.logError((results && results.message) || '操作失败,请重新登录');
                        }

                    })
                })
            };

            var init = function () {
                    contentService.queryMenus().then(function(results){
                        if(!results || results.code != 0){
                            logger.logError((results && results.message) || '查询数据失败,请重新登录');
                            return;
                        }
                        $scope.menus = results.data || [];
                        $scope.selectedMenu = $scope.menus.length > 0 ? $scope.menus[0] : {};

                        $scope.search();

                    })
            };
            init();
        }])

    .controller('editContentCtrl', ['$scope', '$commonService','contentService', '$routeParams', 'logger', 'cfpLoadingBar','$location',
        function ($scope, $commonService, contentService, $routeParams, logger, cfpLoadingBar, $location) {
            $scope.contentId = $routeParams.contentId;
            $scope.menus = [];
            $scope.subMenus = [];
            $scope.filterSubbMenus = [];
            if(!!$scope.contentId){
                contentService.getContent($scope.contentId).then(function (results) {
                    if(!results || results.code != 0){
                        logger.logError((results && results.message) || '查询数据失败,请重新登录');
                        return;
                    }
                    $scope.content =  results.data;

                    setTimeout(function () {
                        $scope.contentEditor = $commonService.getContentEditor();
                        $scope.contentEditor.$txt.html($scope.content.content);
                        $scope.$apply();
                    },100);
                })
            }
            else{
                $scope.content = {type: 'article', stick: 'N'};
                setTimeout(function () {
                    $scope.contentEditor = $commonService.getContentEditor();
                    $scope.$apply();

                },100);
            }
            
            $scope.changeMenu = function () {
                $scope.content.subMenuId = '';
                var _filterSubMenus = [];
                for(var index = 0; index < $scope.subMenus.length; index++){
                    if($scope.subMenus[index].parentMenuId == $scope.content.menuId){
                        _filterSubMenus.push($scope.subMenus[index]);
                    }
                }
                $scope.filterSubMenus = _filterSubMenus;

            }

            $scope.imgUploadCallback = function () {
                $scope.$apply();
            };


            $scope.saveContent = function(){
                if($scope.contentEditor){
                    $scope.content.content = $scope.contentEditor.$txt.html();
                }
                if(!!$scope.content.id){
                    contentService.modifyContent($scope.content).then(function (results) {
                        if(!results || results.code != 0){
                            logger.logError((results && results.message) || '操作数据失败,请重新登录');
                            return;
                        }
                        logger.logSuccess('保存成功');

                    });
                }
                else{
                    contentService.addContent($scope.content).then(function (results) {
                        if(!results || results.code != 0){
                            logger.logError((results && results.message) || '操作数据失败,请重新登录');
                            return;
                        }
                        logger.logSuccess('保存成功');
                        debugger;
                        $location.path('/contents/edit/'+results.data.id);
                    })
                }

                console.log(JSON.stringify($scope.content));
            }

            contentService.queryMenus().then(function (results) {
                if(results && results.code == 0){
                    $scope.menus = results.data;
                }
            });
            contentService.querySubMenus().then(function (results) {
                if(results && results.code == 0){
                    $scope.subMenus  = results.data;
                    $scope.filterSubMenus = results.data;
                }
            });

        }])
    .controller('deleteComponentCtrl', ['$scope', '$uibModalInstance', 'data',
        function ($scope,$uibModalInstance, data) {
            $scope.data = data;
            $scope.ok = function() {
                $uibModalInstance.close( $scope.data.id);
            };
            $scope.cancel = function() {
                $uibModalInstance.dismiss("cancel");
            };

        }])
    .factory('contentService', ['$http', function ($http) {
        return {
            queryAllContents: function (menuId) {
                return $http({
                    method: "GET",
                    url: "/management/contents",
                    params: {
                        menuId : menuId
                    }
                }).then(function (results) {
                    return results.data;
                })
            },
            getContent: function (contentId) {
                return $http({
                    method: "GET",
                    url: "/management/contents/"+contentId,
                }).then(function (results) {
                    return results.data;
                })
            },
            addContent: function (content) {
                return $http({
                    method: "POST",
                    url: "/management/contents/",
                    data: content
                }).then(function (results) {
                    return results.data;
                })
            },
            modifyContent: function (content) {
                return $http({
                    method: "PUT",
                    url: "/management/contents/"+content.id,
                    data: content
                }).then(function (results) {
                    return results.data;
                })
            },

            deleteContent: function (contentId) {
                return $http({
                    method: "DELETE",
                    url: "/management/contents/"+contentId
                }).then(function (results) {
                    return results.data;
                })
            },
            queryMenus: function () {
                return $http({
                    method: "GET",
                    url: "/management/menus"
                }).then(function (results) {
                    return results.data;
                })
            },

            querySubMenus: function () {
                return $http({
                    method: "GET",
                    url: "/management/menus/subMenus"
                }).then(function (results) {
                    return results.data;
                })}
        }
    }]);